package com.fira.quartz.task;

import com.fira.common.constant.Constants;
import com.fira.common.utils.DateUtils;
import com.fira.common.utils.uuid.IdUtils;
import com.fira.edu.domain.EduCourse;
import com.fira.edu.domain.EduCourseSchedule;
import com.fira.edu.domain.EduCourseScheduleTime;
import com.fira.edu.service.IEduCourseScheduleService;
import com.fira.edu.service.IEduCourseScheduleTimeService;
import com.fira.edu.service.IEduCourseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 生成租户下每周的排课信息
 * @author tony
 * @date 2021-10-18
 */
@Component("classScheduleTimeTask")
public class EduClassScheduleTimeTask {
    private static final Logger log = LoggerFactory.getLogger(EduClassScheduleTimeTask.class);
    @Autowired
    private IEduCourseScheduleService eduCourseScheduleService;
    @Autowired
    private IEduCourseScheduleTimeService eduCourseScheduleTimeService;
    @Autowired
    private IEduCourseService eduCourseService;

    public void createScheduleTime(){
        /**
         * 1、先查询edu_course_schedule 和 edu_course_schedule_time 排课信息
         * 2、根据edu_course_schedule的课程查询截止日期
         * 3、每周一凌晨生成本周的排课信息 edu_course_schedule_time
         */
        List<EduCourse> courseList = eduCourseService.selectEduCourseList(null);
        if(CollectionUtils.isNotEmpty(courseList) && DateUtils.getEnWeekNum(DateUtils.getNowDate()) == 1){
            //查询每个课程对应的排课信息
            courseList.forEach(item -> {
                getCourseScheduleList(item);
            });
        }
    }

    public void processNewScheduleTime(){
        /**
         * 1、查询出所有edu_course_schedule_time表中course_date为空的数据
         * 2、查询到父级edu_course_schedule的course_date日期
         * 3、根据edu_course_schedule_time数据中的course_week算出日期更新到course_date字段中
         */
        List<EduCourseScheduleTime> scheduleTimeList = eduCourseScheduleTimeService.selectScheduleTimeList4NullCourseDate();
        if(CollectionUtils.isNotEmpty(scheduleTimeList)){
            EduCourseSchedule courseSchedule = eduCourseScheduleService.selectEduCourseScheduleById(scheduleTimeList.get(0).getCourseScheduleId());
            if(courseSchedule == null) {
                log.error("课程排班courseScheduleId为空");
                return;
            }
            Date startDate = courseSchedule.getCourseDate();
            String startWeek = DateUtils.dateToWeek(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,startDate));
            startWeek = startWeek.replaceAll("星期","周");
            String finalStartWeek = startWeek;
            scheduleTimeList.forEach(item -> {
                if(item.getCourseWeek().equals(finalStartWeek)){
                    item.setCourseDate(startDate);
                }else{
                    Date nextDate = getDateInSameWeek(startDate,item.getCourseWeek());
                    if(nextDate != null){
                        item.setCourseDate(nextDate);
                    }
                }
                eduCourseScheduleTimeService.updateEduCourseScheduleTime(item);
            });
        }
    }

    private void getCourseScheduleList(EduCourse item){
        EduCourseSchedule eduCourseSchedule = new EduCourseSchedule();
        eduCourseSchedule.setCourseId(item.getId());
        List<EduCourseSchedule> courseScheduleList = eduCourseScheduleService.selectEduCourseScheduleList(eduCourseSchedule);
        if(CollectionUtils.isNotEmpty(courseScheduleList)){
            //查询排课明细
            courseScheduleList.forEach(schedule -> {
                createCourseScheduleTime(schedule);
            });
        }
    }

    private void createCourseScheduleTime(EduCourseSchedule courseSchedule){
        EduCourseScheduleTime courseScheduleTime = new EduCourseScheduleTime();
        courseScheduleTime.setCourseScheduleId(courseSchedule.getId());
        List<EduCourseScheduleTime> courseScheduleTimeList = eduCourseScheduleTimeService.selectEduCourseScheduleTimeList(courseScheduleTime);
        if(CollectionUtils.isNotEmpty(courseScheduleTimeList)){
            courseScheduleTimeList.forEach(item -> {
                //创建课程排课信息
                Date now = DateUtils.getNowDate();
                //查询本周日期
                List<Date> currentWeekDays = DateUtils.getWeekAllDates(now);
                currentWeekDays.forEach(weekDay -> {
                    String week = DateUtils.dateToWeek(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,weekDay));
                    week = week.replace("星期","周");
                    if(item.getCourseWeek().equals(week)){
                        //先查询这天是否已存在排课记录,若存在则不处理
                        EduCourseScheduleTime eduCourseScheduleTime = new EduCourseScheduleTime();
                        eduCourseScheduleTime.setCourseScheduleId(item.getCourseScheduleId());
                        eduCourseScheduleTime.setCourseDate(weekDay);
                        if(CollectionUtils.isEmpty(eduCourseScheduleTimeService.selectEduCourseScheduleTimeList(eduCourseScheduleTime))){
                            addCourseScheduleTime(weekDay,item);
                        }
                    }
                });
            });
        }
    }

    public void addCourseScheduleTime(Date courseDate,EduCourseScheduleTime reference){
        EduCourseScheduleTime courseScheduleTime = new EduCourseScheduleTime();
        courseScheduleTime.setCourseDate(courseDate);
        courseScheduleTime.setCourseWeek(reference.getCourseWeek());
        courseScheduleTime.setCourseScheduleId(reference.getCourseScheduleId());
        courseScheduleTime.setCourseStartTime(reference.getCourseStartTime());
        courseScheduleTime.setCourseEndTime(reference.getCourseEndTime());
        courseScheduleTime.setCourseStatus(Constants.STATUS_ZERO);
        courseScheduleTime.setCourseHours(reference.getCourseHours());
        courseScheduleTime.setId(IdUtils.fastSimpleUUID());
        courseScheduleTime.setCreateTime(DateUtils.getNowDate());
        eduCourseScheduleTimeService.insertEduCourseScheduleTime(courseScheduleTime);
    }

    /**
     * 获取一周内匹配周几的日期
     * @param startDate
     * @param week
     * @return
     */
    private Date getDateInSameWeek(Date startDate,String week){
        for(int i=1;i<=6;i++){
            Date nextDate = DateUtils.addDays(startDate,i);
            String startWeek = DateUtils.dateToWeek(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,nextDate));
            startWeek = startWeek.replaceAll("星期","周");
            if(startWeek.equals(week)){
                return nextDate;
            }else{
                continue;
            }
        }
        return null;
    }
}
